﻿/// Jasig CAS server emulation with ASP.NET
/// by Uli Trampe
/// http://jasigemu.codeplex.com/
/// 
using System;
using System.Web.Security;
using Codeplex.JasigEmu;

namespace CasEmulator
{
    public partial class Login : System.Web.UI.Page, ICasAuthenticator
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.IsPostBack) return;

            // handle everything that deals with CAS
            CasServer.HandlePageLoad(this);
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            string strUserName = this.editUserName.Text;
            string strPassWord = this.editPassWord.Text;
            
            // validate user name and password
            if (PerformAuthentication(strUserName, strPassWord))
            {
                // check if this is a CAS request and handle it
                if (CasServer.HandlePageLogin(this, strUserName, this.doRemember.Checked)) return;

                // if not, do it the FormsAuthentication way
                FormsAuthentication.RedirectFromLoginPage(strUserName, this.doRemember.Checked);
            }
            else
            {
                this.textFailed.Visible = true;
            }
        }

        protected bool PerformAuthentication(string strUserName, string strPassWord)
        {
            // perform the 'orinal' Jasig CAS authentication: grant everyone access to the page 
            // who is able to type any username twice
            return strUserName != "" && strUserName == strPassWord;
        }

        #region ICasAuthenticator Members

        bool ICasAuthenticator.CasCheckPermission(string strUserName, string strService)
        {
            // no restrictions by default
            return true;
        }

        void ICasAuthenticator.CasLogin(string strUserName, bool doRemember)
        {
            // sign in via forms authentication
            FormsAuthentication.SetAuthCookie(strUserName, doRemember);
        }

        void ICasAuthenticator.CasLogout()
        {
            // sing out forms authentication
            FormsAuthentication.SignOut();

            // we cannot call FormsAuthentication.RedirectToLoginPage here because it would append a ReturnUrl parameter
            this.Response.Redirect(FormsAuthentication.LoginUrl);
        }

        string ICasAuthenticator.CasTranslateService(string strService)
        {
            // no additional translation by default
            return strService;
        }

        #endregion

    }
}
